# -*- coding: utf-8 -*-
import os
import sys

import pymysql
from dbutils.pooled_db import PooledDB

path = os.path.abspath(__file__)
sys.path.extend([path, os.path.dirname(path), os.path.dirname(os.path.dirname(path))])
from core import settings


class MysqlPool:

    def __init__(self, db='stock'):
        """
        @summary: 初始化数据库连接池
        :param db: 数据库名称
        """
        self.config = {
            "charset": 'utf8mb4',
            "mincached": 10,
            "maxcached": 10,
            "maxshared": 20,
            "blocking": True,
            "maxusage": 0,
            "setsession": None,
            "reset": False,
            "ping": 1,
            "use_unicode": True,
            'creator': pymysql,
            'host': settings.mysql(db)['host'],
            'port': int(settings.mysql(db)['port']),
            'user': settings.mysql(db)['username'],
            'password': settings.mysql(db)['password'],
            'db': settings.mysql(db)['databases'],
            'maxconnections': 100,  # 连接池最大连接数量
            'cursorclass': pymysql.cursors.DictCursor
        }
        self.pool = PooledDB(**self.config)
        self.conn = self.pool.connection()
        self.cur = self.conn.cursor()

    def select(self, sql, param=None):
        if param is None:
            count = self.cur.execute(sql)
        else:
            count = self.cur.execute(sql, param)
        if count > 0:
            result = self.cur.fetchmany(count)  # 从结果集中获取几行。
        else:
            result = False
        return result

    def insert_many(self, sql, values):
        count = self.cur.executemany(sql, values)
        return count

    def __query(self, sql, param=None):
        if param is None:
            count = self.cur.execute(sql)
        else:
            count = self.cur.execute(sql, param)
        return count

    def update(self, sql, param=None):
        return self.__query(sql, param)

    def insert(self, sql, param=None):
        return self.__query(sql, param)

    def delete(self, sql, param=None):
        return self.__query(sql, param)

    def begin(self):
        """
        @summary: 开启事务
        """
        self.conn.autocommit(0)

    def end(self, option='commit'):
        """
        @summary: 结束事务
        """
        if option == 'commit':
            self.conn.commit()
        else:
            self.conn.rollback()

    def closes(self, isEnd=1):
        """
        @summary: 释放连接池资源
        """
        if isEnd == 1:
            self.end('commit')
        else:
            self.end('rollback')
        self.cur.close()
        self.conn.close()
